package best.driver.android.Activity.Order;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.*;
import best.driver.android.*;
import best.driver.android.Beans.*;
import best.driver.android.Event.NewOrderCanceledEvent;
import best.driver.android.Event.OrderFeeEvent;
import best.driver.android.Event.OrderRouteChangeEvent;
import best.driver.android.Event.UploadFileEvent;
import best.driver.android.Map.location.LastKnowLocation;
import best.driver.android.Model.OrderDetailModel;
import best.driver.android.Utils.Logger;
import best.driver.android.Utils.TimeUtil;
import best.driver.android.Utils.Util;
import best.driver.android.View.*;
import best.driver.android.View.photocrop.PhotoBase;
import best.driver.android.common.app.AppProxyFactory;
import best.driver.android.common.network.ApiObjectRequest;
import best.driver.android.common.network.ApiRequest;
import best.driver.android.common.network.BestApiError;
import best.driver.android.common.network.BestError;
import best.driver.android.manager.OrderManager;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import com.activeandroid.query.Select;
import com.baidu.mapapi.model.LatLng;
import de.greenrobot.event.EventBus;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class OrderOperationActivity extends PhotoBase {

    private OrderDetailInfo mOrderDetail;

    private long mStartTime = 0;

    private String mLoadingPicFileId;

    private String mReturnPicFileId;

    private String mOrderId;

    private Timer mTimer;
    private TimerTask mTimerTask;

    private Timer mCalculateFeeTimer;
    private TimerTask mCalculateFeeTimerTask;

    private boolean mIsCountingTime = true;

    @InjectView(R.id.tv_photo_hint)
    TextView mTvPhotoHint;

    @InjectView(R.id.best_map_view)
    BestMapView mMapView;

    @InjectView(R.id.tv_cost)
    TextView mTvCost;

    @InjectView(R.id.btn_operate_order)
    Button mBtnOperateOrder;

    @InjectView(R.id.tv_load_address)
    TextView mTvLoadAddress;

    @InjectView(R.id.tv_unload_address)
    TextView mTvUnloadAddress;

    @InjectView(R.id.ll_load_complete_img)
    LinearLayout mLinearLoadCompleteImg;

    @InjectView(R.id.iv_take_photo)
    ImageView mIvPhoto;

    @InjectView(R.id.tv_time_calculate)
    TextView mTvTimeCalculate;

    @InjectView(R.id.tv_cost_hint)
    TextView mTvCostHint;

    @InjectView(R.id.tv_cost_pre)
    TextView mTvCostPre;

    @InjectView(R.id.tv_price_detail)
    TextView mTvPriceDetail;

    @InjectView(R.id.ll_wait_hint)
    LinearLayout mLinearWaitHint;

    @InjectView(R.id.iv_status)
    ImageView mIvStatus;

    @InjectView(R.id.tv_status)
    TextView mTvStatus;

    @InjectView(R.id.tv_load_multi)
    TextView mTvLoadMulti;

    @InjectView(R.id.tv_unload_multi)
    TextView mTvUnloadMulti;

    @OnClick(R.id.tv_price_detail)
    protected void showPriceDetail() {
        if (mOrderDetail != null) {
            Intent intent = new Intent(OrderOperationActivity.this, OrderFeeActivity.class);
            intent.putExtra("orderId", mOrderDetail.orderId);
            startActivity(intent);
        }
    }

    @OnClick(R.id.ll_order_detail)
    protected void gotoOrderDetail() {
        Intent intent = new Intent(OrderOperationActivity.this, OrderDetailActivity.class);
        intent.putExtra("orderId", mOrderDetail.orderId);
        startActivity(intent);
    }

    @OnClick(R.id.iv_phones)
    protected void showPhones() {
        if (mOrderDetail != null && mOrderDetail.orderAddresses != null && mOrderDetail.orderAddresses.size() > 0) {
            //SelectThreeDialog dialog = new SelectThreeDialog(OrderOperationActivity.this, mOrderDetail.orderAddresses);
            OrderAddresses address = new OrderAddresses();
            address.flag = "MAKER";
            address.phone = mOrderDetail.shipper.phone;
            List<OrderAddresses> addressesList = new ArrayList<OrderAddresses>();
            addressesList.addAll(mOrderDetail.orderAddresses);
            addressesList.add(address);
            SelectPhoneDialog dialog = new SelectPhoneDialog(OrderOperationActivity.this, addressesList);
        }
    }

    @OnClick(R.id.btn_operate_order)
    protected void operateOrder() {
        if (!TextUtils.isEmpty(mOrderDetail.nextStatus)) {
            if (mOrderDetail.nextStatus.equals(OrderStatus.STARTED)) {
                startOrder();
            } else if (mOrderDetail.nextStatus.equals(OrderStatus.LOADING)) {
                gotoLoading();
            } else if (mOrderDetail.nextStatus.equals(OrderStatus.IN_TRANSIT)) {
                transport();
            } else if (mOrderDetail.nextStatus.equals(OrderStatus.UNLOADING)) {
                final ConfirmDialog dialog = new ConfirmDialog(OrderOperationActivity.this, "是否确定到达卸货地");
                dialog.setListener(new ConfirmDialogListener() {
                    @Override
                    public void onClickConfirm() {
                        dialog.dismiss();
                        unLoading();
                    }
                });
            } else if (mOrderDetail.nextStatus.equals(OrderStatus.RETURNING)) {
                returnBack();
            } else if (OrderStatus.RETURNING.equals(mOrderDetail.status)) {
                OrderOperationActivity.this.finish();
            } else if (OrderStatus.FINISHED.equals(mOrderDetail.nextStatus)) {
                completeOrder();
            } else if (mOrderDetail.status.equals(OrderStatus.CANCELED)) {
                OrderOperationActivity.this.finish();
            }
        } else {
            if (OrderStatus.CANCELED.equals(mOrderDetail.status)) {
                OrderOperationActivity.this.finish();
            } else if (OrderStatus.FINISHED.equals(mOrderDetail.status)) {
                OrderOperationActivity.this.finish();
            }
        }
    }

    @OnClick(R.id.iv_take_photo)
    protected void takePhoto() {
        if (OrderStatus.LOADING.equals(mOrderDetail.status)) {
            gotoSelectPhoto(mIvPhoto, 6);
        } else if (OrderStatus.UNLOADING.equals(mOrderDetail.status)) {
            gotoSelectPhoto(mIvPhoto, 7);
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.activity_order_operation);
        ButterKnife.inject(this, view);
        view.setVisibility(View.GONE);
        EventBus.getDefault().register(this);
        getDate(false);
        setTopTopic("订单详情");
        setLeftIvBak(R.drawable.icon_navibar_back);
    }


    private void getDate(boolean isFromSocket) {
        showWaiting();
        if (!isFromSocket) {
            String orderId = getIntent().getStringExtra("orderId");
            mOrderId = orderId;
        }
        if (!TextUtils.isEmpty(mOrderId)) {
            ApiObjectRequest<OrderDetailInfo> request = RequestFactory.createGetOrderDetailInfoRequest(mOrderId);
            request.setListener(new ApiRequest.ApiRequestListener<OrderDetailInfo>() {
                @Override
                public void onRequestSuccess(OrderDetailInfo response) {
                    mOrderDetail = response;
                    view.setVisibility(View.VISIBLE);
                    if (response != null && !OrderStatus.WAIT_START.equals(response.status) && !OrderStatus.STARTED.equals(response.status)) {
                        startCalculateFeeTimer(120000);
                        if (response.actualPrice > 0.1) {
                            setPrice(response.actualPrice, false);
                            //mTvCost.setText(response.actualPrice + "元");
                        }
                    } else if (response != null && OrderStatus.RETURNING.equals(response.status)) {
                        setPrice(response.actualPrice, false);
                        //mTvCost.setText(response.actualPrice + "元");
                    } else {
                        if (response.actualPrice > 0.1) {
                            setPrice(response.actualPrice, false);
                            //mTvCost.setText(response.actualPrice + "元");
                        } else {
                            setPrice(response.estimatePrice, true);
                            //mTvCost.setText(response.estimatePrice + "元(预估)");
                        }
                    }

                    if (response != null && response.familiarPrice > 0.1) {
                        mTvCostPre.setText("一口价");
                        mTvCost.setText(response.familiarPrice + "元");
                    }
                    if (!TextUtils.isEmpty(PayType.getInstance().getPayTypeMap().get(response.paymentMethod))) {
                        mTvCostHint.setText("(" + PayType.getInstance().getPayTypeMap().get(response.paymentMethod) + ")");
                    }
                    getOrderPrice(getCurrentOrder());
                    updateView(mOrderDetail);
                    setRouteView(response);
                    hideWaiting();
                }

                @Override
                public void onRequestError(BestError error) {
                    hideWaiting();
                    if (error instanceof BestApiError) {
                        AppInfo.showToast(OrderOperationActivity.this, ((BestApiError) error).getErrorMessage());
                    }
                }
            });
            AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);
        }
    }

    private void startOrder() {
        mBtnOperateOrder.setEnabled(false);
        showWaiting();
        ApiObjectRequest<OrderOperationPair> request = RequestFactory.createStartupRequest(mOrderDetail.orderId, BestApp.getInstance().getPosition());
        request.setListener(new ApiRequest.ApiRequestListener<OrderOperationPair>() {
            @Override
            public void onRequestSuccess(OrderOperationPair response) {
                mBtnOperateOrder.setEnabled(true);
                hideWaiting();
                OrderDetailModel model;
                List<OrderDetailModel> models = new Select().from(OrderDetailModel.class).where("orderId = ?", mOrderDetail.orderId).execute();
                if (models != null && models.size() > 0) {
                    model = models.get(0);
                } else {
                    model = new OrderDetailModel();
                }
                LastKnowLocation location = BestApp.getInstance().getLastKnowLocation();
                if (System.currentTimeMillis() - location.mTimeStamp < 150000) {
                    model.lastLat = location.mLat;
                    model.lastLng = location.mLng;
                    model.startLat = location.mLat;
                    model.startLng = location.mLng;
                }
                model.orderId = mOrderDetail.orderId;
                model.startTime = System.currentTimeMillis();
                model.distance = 0;
                model.save();
                startCalculateFeeTimer(120000);
                mBtnOperateOrder.setText(response.action);
                mOrderDetail.status = response.currentStatus;
                mOrderDetail.nextStatus = response.nextStatus;
                OrderManager.getInstance().setCurrentOrder(mOrderDetail);
                setTitleDesc(response.processStatus);
                getOrderPrice(getCurrentOrder());
                showCancelViewOrNot();
                if (!TextUtils.isEmpty(OrderStatus.getInstance().getOrderStatusMap().get(response.currentStatus))) {
                    setTopTopic(OrderStatus.getInstance().getOrderStatusMap().get(response.currentStatus));
                }
                getOrderPrice(getCurrentOrder());

            }

            @Override
            public void onRequestError(BestError error) {
                mBtnOperateOrder.setEnabled(true);
                if (error instanceof BestApiError) {
                    AppInfo.showToast(OrderOperationActivity.this, ((BestApiError) error).getErrorMessage());
                }
                hideWaiting();
            }
        });
        AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);

    }

    private void transport() {
//        if (TextUtils.isEmpty(mReturnPicFileId) && OrderStatus.UNLOADING.equals(mOrderDetail.status)) {
//            AppInfo.showToast(this, "请上传回单照片");
//            return;
//        }
        mBtnOperateOrder.setEnabled(false);
        showWaiting();
        if (!TextUtils.isEmpty(mOrderDetail.orderId)) {

            OrderDetailModel model = getCurrentOrder();
            int distance = 0;
            int waitTime = 0;
            LatLng latLng = new LatLng(0, 0);
            if (model != null) {
                distance = (int) model.distance;
                waitTime = (int) (model.waitTime / 1000);
                latLng = new LatLng(model.lastLat, model.lastLng);
            }

            final ApiObjectRequest<OrderOperationPair> request = RequestFactory.createTransitRequest(mOrderDetail.orderId, null, BestApp.getInstance().getPosition());
            //final ApiObjectRequest<OrderOperationPair> request = RequestFactory.createTransitRequest(mOrderDetail.orderId, mReturnPicFileId, BestApp.getInstance().getPosition());
            request.setListener(new ApiRequest.ApiRequestListener<OrderOperationPair>() {
                @Override
                public void onRequestSuccess(OrderOperationPair response) {
                    mBtnOperateOrder.setEnabled(true);
                    mReturnPicFileId = null;
                    hideWaiting();
                    endCountingTime();
                    showTransitingView();
                    mBtnOperateOrder.setText(response.action);
                    mOrderDetail.status = response.currentStatus;
                    mOrderDetail.nextStatus = response.nextStatus;
                    OrderManager.getInstance().setCurrentOrder(mOrderDetail);
                    setTitleDesc(response.processStatus);
                    showCancelViewOrNot();

                    if (!TextUtils.isEmpty(OrderStatus.getInstance().getOrderStatusMap().get(response.currentStatus))) {
                        setTopTopic(OrderStatus.getInstance().getOrderStatusMap().get(response.currentStatus));
                    }
                    getOrderPrice(getCurrentOrder());
                }

                @Override
                public void onRequestError(BestError error) {
                    mBtnOperateOrder.setEnabled(true);
                    if (error instanceof BestApiError) {
                        AppInfo.showToast(OrderOperationActivity.this, ((BestApiError) error).getErrorMessage());
                    }
                    hideWaiting();
                }
            });
            AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);
        }
    }

    protected void unLoading() {
        mBtnOperateOrder.setEnabled(false);
        showWaiting();
        if (!TextUtils.isEmpty(mOrderDetail.orderId)) {
            final ApiObjectRequest<OrderOperationPair> request = RequestFactory.createUnloadingRequest(mOrderDetail.orderId, BestApp.getInstance().getPosition());
            request.setListener(new ApiRequest.ApiRequestListener<OrderOperationPair>() {
                @Override
                public void onRequestSuccess(OrderOperationPair response) {
                    mBtnOperateOrder.setEnabled(true);
                    startCountingTime();
                    hideWaiting();
                    showUnloadingView();
                    OrderDetailModel model;
                    List<OrderDetailModel> models = new Select().from(OrderDetailModel.class).where("orderId = ?", mOrderDetail.orderId).execute();

                    mOrderDetail.status = response.currentStatus;
                    mOrderDetail.nextStatus = response.nextStatus;
                    //if(OrderStatus.RETURNING.equals(mOrderDetail.nextStatus)) {
//                    showTakePhotoLayout();
//                    mTvPhotoHint.setText("请在收货人在回单上签字后拍摄回单，请保证拍摄的照片字迹清晰，否则会被处罚。无回单请拍摄卸货后照片");
                    mBtnOperateOrder.setText(response.action);
//                    } else {
//                        mBtnOperateOrder.setText(response.action);
//                    }
                    OrderManager.getInstance().setCurrentOrder(mOrderDetail);
                    setTitleDesc(response.processStatus);
                    showCancelViewOrNot();

                    if (!TextUtils.isEmpty(OrderStatus.getInstance().getOrderStatusMap().get(response.currentStatus))) {
                        setTopTopic(OrderStatus.getInstance().getOrderStatusMap().get(response.currentStatus));
                    }
                    getOrderPrice(getCurrentOrder());
                    if (models != null && models.size() > 0) {
                        model = models.get(0);
                    } else {
                        return;
                    }
//                    LastKnowLocation location = BestApp.getInstance().getLastKnowLocation();
//                    if (System.currentTimeMillis() - location.mTimeStamp < 30000) {
//                        model.lastLat = location.mLat;
//                        model.lastLng = location.mLng;
//                        model.startLat = location.mLat;
//                        model.startLng = location.mLng;
//                    }
                    //model.orderId = mOrderDetail.orderId;
                    model.startLoadTime = System.currentTimeMillis();
                    model.startTime = System.currentTimeMillis();
                    model.save();

                }

                @Override
                public void onRequestError(BestError error) {
                    mBtnOperateOrder.setEnabled(true);
                    if (error instanceof BestApiError) {
                        AppInfo.showToast(OrderOperationActivity.this, ((BestApiError) error).getErrorMessage());
                    }
                    hideWaiting();
                }
            });
            AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);
        }
    }

    protected void returnBack() {
        mBtnOperateOrder.setEnabled(false);
        showWaiting();
        if (!TextUtils.isEmpty(mOrderDetail.orderId)) {
            final OrderDetailModel model = getCurrentOrder();
            int distance = 0;
            int waitTime = 0;
            model.waitTime += System.currentTimeMillis() - model.startTime;

            LatLng latLng = new LatLng(0, 0);
            if (model != null) {
                distance = (int) model.distance;
                waitTime = (int) (model.waitTime / 1000);
                latLng = new LatLng(model.lastLat, model.lastLng);
            }
            Logger.d("distance_return_pre", distance + "米");

//            ApiObjectRequest<OrderOperationPair> request = RequestFactory.createReturnBackRequest(mOrderDetail.orderId,
//                    mReturnPicFileId, BestApp.getInstance().getPosition(), distance * AppConfig.DISTANCE_INTERVAL, waitTime * AppConfig.TIME_INTERVAL);
            ApiObjectRequest<OrderOperationPair> request = RequestFactory.createReturnBackRequest(mOrderDetail.orderId,
                    null, BestApp.getInstance().getPosition(), distance * AppConfig.DISTANCE_INTERVAL, waitTime * AppConfig.TIME_INTERVAL);
            request.setListener(new ApiRequest.ApiRequestListener<OrderOperationPair>() {
                @Override
                public void onRequestSuccess(OrderOperationPair response) {
                    mReturnPicFileId = null;
                    model.save();
                    mBtnOperateOrder.setEnabled(true);
                    hideWaiting();
                    endCountingTime();
                    mBtnOperateOrder.setText(response.action);
                    if (TextUtils.isEmpty(response.action)) {
                        mBtnOperateOrder.setText("返回");
                    }
                    mOrderDetail.status = response.currentStatus;
                    mOrderDetail.nextStatus = response.nextStatus;
                    OrderManager.getInstance().setCurrentOrder(mOrderDetail);
                    setTitleDesc(response.processStatus);
                    showCancelViewOrNot();
                    showAfterReturnView();

                    if (!TextUtils.isEmpty(OrderStatus.getInstance().getOrderStatusMap().get(response.currentStatus))) {
                        setTopTopic(OrderStatus.getInstance().getOrderStatusMap().get(response.currentStatus));
                    }
                    if (mOrderDetail.familiarPrice < 0.1) {
                        mTvPriceDetail.setVisibility(View.VISIBLE);
                    }
                    getOrderPrice(getCurrentOrder());
                }

                @Override
                public void onRequestError(BestError error) {
                    mBtnOperateOrder.setEnabled(true);
                    hideWaiting();
                    if (error instanceof BestApiError) {
                        AppInfo.showToast(OrderOperationActivity.this, ((BestApiError) error).getErrorMessage());
                    }
                }
            });
            AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);
        }
    }

    protected void completeOrder() {
//        if (TextUtils.isEmpty(mReturnPicFileId)) {
//            AppInfo.showToast(this, "请上传回单照片");
//            return;
//        }
        mBtnOperateOrder.setEnabled(false);
        showWaiting();
        if (!TextUtils.isEmpty(mOrderDetail.orderId)) {
            final OrderDetailModel model = getCurrentOrder();
            int distance = 0;
            int waitTime = 0;
            model.waitTime += System.currentTimeMillis() - model.startTime;
            LatLng latLng = new LatLng(0, 0);
            if (model != null) {
                distance = (int) model.distance;
                waitTime = (int) (model.waitTime / 1000);
                latLng = new LatLng(model.lastLat, model.lastLng);
            }
            Logger.d("distance_complete_pre", distance + "米");
//            ApiObjectRequest<OrderOperationPair> request = RequestFactory.createCompleteOrder(mOrderDetail.orderId, mReturnPicFileId,
//                    BestApp.getInstance().getPosition(), distance * AppConfig.DISTANCE_INTERVAL, waitTime * AppConfig.TIME_INTERVAL);
            ApiObjectRequest<OrderOperationPair> request = RequestFactory.createCompleteOrder(mOrderDetail.orderId, null,
                    BestApp.getInstance().getPosition(), distance * AppConfig.DISTANCE_INTERVAL, waitTime * AppConfig.TIME_INTERVAL);
            request.setListener(new ApiRequest.ApiRequestListener<OrderOperationPair>() {
                @Override
                public void onRequestSuccess(OrderOperationPair response) {
                    mReturnPicFileId = null;
                    model.save();
                    mBtnOperateOrder.setEnabled(true);
                    endCountingTime();
                    hideWaiting();
                    mBtnOperateOrder.setText(response.action);
                    mBtnOperateOrder.setText("已完成,返回");
                    mOrderDetail.status = response.currentStatus;
                    mOrderDetail.nextStatus = response.nextStatus;
                    //OrderManager.getInstance().deleteCurrentOrder(mOrderDetail.orderId);
                    setTitleDesc(response.processStatus);
                    showFinishedView();
                    showCancelViewOrNot();

                    if (!TextUtils.isEmpty(OrderStatus.getInstance().getOrderStatusMap().get(response.currentStatus))) {
                        setTopTopic(OrderStatus.getInstance().getOrderStatusMap().get(response.currentStatus));
                    }
                    if (mOrderDetail.familiarPrice < 0.1) {
                        mTvPriceDetail.setVisibility(View.VISIBLE);
                    }
                    getOrderPrice(getCurrentOrder());
                }

                @Override
                public void onRequestError(BestError error) {
                    mBtnOperateOrder.setEnabled(true);
                    if (error instanceof BestApiError) {
                        AppInfo.showToast(OrderOperationActivity.this, ((BestApiError) error).getErrorMessage());
                    }
                    hideWaiting();
                }
            });
            AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);
        }
    }

    protected void gotoLoading() {
        mBtnOperateOrder.setEnabled(false);
        showWaiting();
        if (!TextUtils.isEmpty(mOrderDetail.orderId)) {
            ApiObjectRequest<OrderOperationPair> request = RequestFactory.createLoadingRequest(mOrderDetail.orderId, BestApp.getInstance().getPosition());
            request.setListener(new ApiRequest.ApiRequestListener<OrderOperationPair>() {
                @Override
                public void onRequestSuccess(OrderOperationPair response) {
                    mBtnOperateOrder.setEnabled(true);
                    startCountingTime();
                    hideWaiting();
                    showLoadingView();
                    mBtnOperateOrder.setText(response.action);
                    mOrderDetail.status = response.currentStatus;
                    mOrderDetail.nextStatus = response.nextStatus;
                    OrderDetailModel model;
                    List<OrderDetailModel> models = new Select().from(OrderDetailModel.class).where("orderId = ?", mOrderDetail.orderId).execute();
                    if (models != null && models.size() > 0) {
                        model = models.get(0);
                    } else {
                        model = new OrderDetailModel();
                    }
                    LastKnowLocation location = BestApp.getInstance().getLastKnowLocation();
                    if (System.currentTimeMillis() - location.mTimeStamp < 15000) {
                        model.lastLat = location.mLat;
                        model.lastLng = location.mLng;
                    }
                    model.orderId = mOrderDetail.orderId;
                    model.startLoadTime = System.currentTimeMillis();
//                    model.distance = 0;
                    model.save();
                    getOrderPrice(model);
                    setTitleDesc(response.processStatus);

                    if (!TextUtils.isEmpty(OrderStatus.getInstance().getOrderStatusMap().get(response.currentStatus))) {
                        setTopTopic(OrderStatus.getInstance().getOrderStatusMap().get(response.currentStatus));
                    }
                    getOrderPrice(getCurrentOrder());
                }

                @Override
                public void onRequestError(BestError error) {
                    mBtnOperateOrder.setEnabled(true);
                    if (error instanceof BestApiError) {
                        AppInfo.showToast(OrderOperationActivity.this, ((BestApiError) error).getErrorMessage());
                    }
                    hideWaiting();
                }
            });
            AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);
        }

    }

    private void updateView(OrderDetailInfo orderDetail) {
        if (orderDetail != null) {
            if (!TextUtils.isEmpty(OrderStatus.getInstance().getOrderStatusMap().get(mOrderDetail.status))) {
                setTopTopic(OrderStatus.getInstance().getOrderStatusMap().get(mOrderDetail.status));
            }
            if (!TextUtils.isEmpty(mOrderDetail.processStatus)) {
                setTitleDesc(mOrderDetail.processStatus);
            }
            showCancelViewOrNot();
            List<OrderAddresses> addresses = orderDetail.orderAddresses;
            boolean isFirstLoad = true;
            for (int i = 0; i < addresses.size(); i++) {
                OrderAddresses address = addresses.get(i);
                if (OrderStatus.SHIPPER_ADDRESS.equals(address.flag)) {
                    if (isFirstLoad) {
                        mTvLoadAddress.setText(address.address);
                    }
                    isFirstLoad = false;
                } else if (OrderStatus.RECEIVER_ADDRESS.equals(address.flag)) {
                    mTvUnloadAddress.setText(address.address);

                }
            }

            if (OrderStatus.ONE_TO_ONE.equals(orderDetail.transportMode)) {
                mTvLoadMulti.setVisibility(View.GONE);
                mTvUnloadMulti.setVisibility(View.GONE);
            } else if (OrderStatus.ONE_TO_N.equals(orderDetail.transportMode)) {
                mTvLoadMulti.setVisibility(View.GONE);
                mTvUnloadMulti.setVisibility(View.VISIBLE);
            } else if (OrderStatus.N_TO_ONE.equals(orderDetail.transportMode)) {
                mTvLoadMulti.setVisibility(View.VISIBLE);
                mTvUnloadMulti.setVisibility(View.GONE);
            } else {
                mTvLoadMulti.setVisibility(View.GONE);
                mTvUnloadMulti.setVisibility(View.GONE);
            }

            if (!TextUtils.isEmpty(mOrderDetail.action)) {
                mBtnOperateOrder.setText(mOrderDetail.action);
            }
            if (OrderStatus.STARTED.equals(mOrderDetail.nextStatus)) {
                showStartView();
                //mOrderDetail.status = OrderStatus.WAIT_START;
            } else if (OrderStatus.LOADING.equals(mOrderDetail.nextStatus)) {
                showArrivingView();
                //mOrderDetail.status = OrderStatus.STARTED;
            } else if (OrderStatus.IN_TRANSIT.equals(mOrderDetail.nextStatus)) {
                showLoadingView();
                if (!OrderStatus.LOADING.equals(mOrderDetail.status)) {
                    hideTakePhotoLayout();
                }
                OrderDetailModel model = getCurrentOrder();
                if (model != null) {
                    mStartTime = model.startTime;
                    startTimer(500);
                }
                //mOrderDetail.status = OrderStatus.LOADING;
            } else if (OrderStatus.UNLOADING.equals(mOrderDetail.nextStatus)) {
                showTransitingView();
                //mOrderDetail.status = OrderStatus.IN_TRANSIT;
            } else if (OrderStatus.FINISHED.equals(mOrderDetail.nextStatus) && OrderStatus.UNLOADING.equals(mOrderDetail.status)) {
                showUnloadingView();
                OrderDetailModel model = getCurrentOrder();
                if (model != null) {
                    mStartTime = model.startTime;
                    startTimer(500);
                }
                //mOrderDetail.status = OrderStatus.UNLOADING;
            } else if (OrderStatus.RETURNING.equals(mOrderDetail.nextStatus)) {
                showReturningView();
                OrderDetailModel model = getCurrentOrder();
                if (model != null) {
                    mStartTime = model.startTime;
                    startTimer(500);
                }
                //mOrderDetail.status = OrderStatus.UNLOADING;
                mBtnOperateOrder.setText(mOrderDetail.action);
            } else if (OrderStatus.FINISHED.equals(mOrderDetail.status)) {
                mBtnOperateOrder.setText(mOrderDetail.action);
                mBtnOperateOrder.setText("已完成,返回");
                if (mOrderDetail.familiarPrice < 0.1) {
                    mTvPriceDetail.setVisibility(View.VISIBLE);
                }
            } else if (OrderStatus.CANCELED.equals(mOrderDetail.status)) {
                mBtnOperateOrder.setText(mOrderDetail.action);
            } else if (OrderStatus.RETURNING.equals(mOrderDetail.status)) {
                mBtnOperateOrder.setText(mOrderDetail.action);
                if (TextUtils.isEmpty(mOrderDetail.action)) {
                    mBtnOperateOrder.setText("返回");
                }
                showAfterReturnView();
                if (mOrderDetail.familiarPrice < 0.1) {
                    mTvPriceDetail.setVisibility(View.VISIBLE);
                }
            } else {
                hideTakePhotoLayout();
            }
            if (OrderStatus.UNLOADING.equals(mOrderDetail.status)) {
                showReturningView();
            }
        }
    }


    private void showWaitingTime() {
        mTvTimeCalculate.setVisibility(View.VISIBLE);
        mLinearWaitHint.setVisibility(View.VISIBLE);
    }

    private void hideWaitingTime() {
        mTvTimeCalculate.setVisibility(View.GONE);
        mLinearWaitHint.setVisibility(View.GONE);
    }

    private void showTakePhotoLayout() {
        mLinearLoadCompleteImg.setVisibility(View.VISIBLE);
        mIvPhoto.setImageResource(R.drawable.icon_photo);
    }

    private void hideTakePhotoLayout() {
        mLinearLoadCompleteImg.setVisibility(View.GONE);
    }

    private void showStatusView() {
        mTvStatus.setVisibility(View.VISIBLE);
        mIvStatus.setVisibility(View.VISIBLE);
    }

    private void hideStatusView() {
        mTvStatus.setVisibility(View.GONE);
        mIvStatus.setVisibility(View.GONE);
    }

    private void setStatusView(int imgId, String content) {
        mIvStatus.setImageResource(imgId);
        mTvStatus.setText(content);
    }

    private void showStartView() {
        mIvStatus.setVisibility(View.GONE);
        mTvStatus.setVisibility(View.GONE);
        hideWaitingView();
        //startTimer(500);
    }

    private void showArrivingView() {
        hideWaitingView();
        mMapView.setVisibility(View.VISIBLE);
        mLinearLoadCompleteImg.setVisibility(View.GONE);
        mIvStatus.setVisibility(View.GONE);
        mTvStatus.setVisibility(View.GONE);
    }

    private void showLoadingView() {
        showWaitingTime();
        mLinearLoadCompleteImg.setVisibility(View.GONE);
        mMapView.setVisibility(View.GONE);
        mIvStatus.setVisibility(View.GONE);
        mTvStatus.setVisibility(View.GONE);
    }


    private void hideWaitingView() {
        mLinearWaitHint.setVisibility(View.GONE);
        mTvTimeCalculate.setVisibility(View.GONE);
    }

    private void showTransitingView() {
        mMapView.setVisibility(View.VISIBLE);
        hideWaitingTime();
        hideTakePhotoLayout();
    }

    private void showUnloadingView() {
        showWaitingTime();
        mMapView.setVisibility(View.GONE);
        mIvStatus.setVisibility(View.GONE);
        mTvStatus.setVisibility(View.GONE);
        hideTakePhotoLayout();
    }

    private void showReturningView() {
        showWaitingTime();
        mMapView.setVisibility(View.GONE);
        //showTakePhotoLayout();
        mTvPhotoHint.setText("请在收货人在回单上签字后拍摄回单，请保证拍摄的照片字迹清晰，否则会被处罚。无回单请拍摄卸货后照片");
        mIvPhoto.setImageResource(R.drawable.icon_photo);
        mIvStatus.setVisibility(View.GONE);
        mTvStatus.setVisibility(View.GONE);
    }

    private void showAfterReturnView() {
        mIvStatus.setVisibility(View.VISIBLE);
        mTvStatus.setVisibility(View.VISIBLE);
        mIvStatus.setImageResource(R.drawable.icon_receipt);
        mTvStatus.setText("请回单/回款给客户");
        hideWaitingTime();
        hideTakePhotoLayout();
        mMapView.setVisibility(View.GONE);
    }

    private void showFinishedView() {
        mIvStatus.setVisibility(View.VISIBLE);
        mTvStatus.setVisibility(View.VISIBLE);
        mIvStatus.setImageResource(R.drawable.icon_complete);
        mTvStatus.setText("已完成");
        hideTakePhotoLayout();
        hideWaitingTime();
        mMapView.setVisibility(View.GONE);
    }

    public void onEventMainThread(OrderDetailModel model) {
        if (model != null && mOrderDetail != null && model.orderId.equals(mOrderDetail.orderId)) {
            getOrderPrice(model);
        }
    }

    public void onEventMainThread(UploadFileEvent event) {
        if (mOrderDetail != null && OrderStatus.LOADING.equals(mOrderDetail.status)) {
            mLoadingPicFileId = event.mFileId;
        } else if (mOrderDetail != null && OrderStatus.RETURNING.equals(mOrderDetail.nextStatus)) {
            mReturnPicFileId = event.mFileId;
        }
        mReturnPicFileId = event.mFileId;
    }

    public void onEventMainThread(OrderFeeEvent event) {
        DecimalFormat df = new DecimalFormat("0.0");
        String price = df.format(event.totalFee);
        if (mOrderDetail != null) {
            if (mOrderDetail != null && !OrderStatus.WAIT_START.equals(mOrderDetail.status) &&
                    !OrderStatus.STARTED.equals(mOrderDetail.status)) {
                setPrice(event.totalFee, false);
                //mTvCost.setText(price + "元");
                mMapView.showDistance();
                mMapView.setDistance((int) (event.distance * AppConfig.DISTANCE_INTERVAL));
            }
        }
    }

    public void onEventMainThread(NewOrderCanceledEvent event) {
        if (mOrderDetail != null && mOrderDetail.orderId.equals(event.orderId)) {
            //OrderManager.getInstance().deleteCurrentOrder(event.orderId);
            final ConfirmDialog dialog = new ConfirmDialog(OrderOperationActivity.this, "订单已被取消");
            dialog.showOnlyOk();
            dialog.setListener(new ConfirmDialogListener() {
                @Override
                public void onClickConfirm() {
                    dialog.dismiss();
                }
            });
            dialog.setDismissListener(new DialogDismissListener() {
                @Override
                public void onDismiss() {
                    OrderOperationActivity.this.finish();
                }
            });
        }
    }

    public void onEventMainThread(OrderRouteChangeEvent event) {
        if (mOrderDetail != null && mOrderDetail.orderId.equals(event.orderId)) {
            getDate(true);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.destroy();
        mIsCountingTime = false;
        stopTimer();
        mIsDestroyed = true;
        stopCalculateTimer();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        OrderDetailInfo currentOrder = OrderManager.getInstance().getCurrentOrder();
        if (currentOrder != null && currentOrder.orderId.equals(mOrderId)) {
            List<OrderDetailModel> models = new Select().from(OrderDetailModel.class).where("orderId = ?", currentOrder.orderId).execute();
            if (models != null && models.size() > 0) {
                OrderDetailModel model = models.get(0);
                getOrderPrice(model);
            }
        }
    }

    public void getOrderPrice(final OrderDetailModel model) {
        if (model == null || mOrderDetail == null || mOrderDetail.familiarPrice > 0.1) {
            return;
        }
        if (!model.orderId.equals(mOrderId)) {
            return;
        }
        long waitTime = 0;
        if (OrderStatus.LOADING.equals(mOrderDetail.status) || OrderStatus.UNLOADING.equals(mOrderDetail.status)) {
            waitTime = (System.currentTimeMillis() - model.startTime + model.waitTime) / 1000;
        } else {
            waitTime = model.waitTime / 1000;
        }
        ApiObjectRequest<OrderFeeInfo> request = RequestFactory.createGetOrderFeeRequest(mOrderDetail.orderId,
                (int) model.distance * AppConfig.DISTANCE_INTERVAL, waitTime * AppConfig.TIME_INTERVAL);
        request.setListener(new ApiRequest.ApiRequestListener<OrderFeeInfo>() {
            @Override
            public void onRequestSuccess(OrderFeeInfo response) {
                OrderFeeEvent event = new OrderFeeEvent(response, model.distance);
                EventBus.getDefault().post(event);
            }

            @Override
            public void onRequestError(BestError error) {

            }
        });
        AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);
    }

    private void updateByTimer() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!mIsCountingTime) {
                    stopTimer();
                } else {
                    if (mStartTime > 1) {
                        //if (OrderStatus.LOADING.equals(mOrderDetail.status) || OrderStatus.UNLOADING.equals(mOrderDetail.status))
                        OrderDetailModel model = getCurrentOrder();
                        long preWaitTime = 0;
                        if (model != null) {
                            preWaitTime = model.waitTime;
                        }
                        mTvTimeCalculate.setText(TimeUtil.convertMillisTime(System.currentTimeMillis() - mStartTime + preWaitTime));
                        mTvTimeCalculate.setVisibility(View.VISIBLE);
                    } else {
                        OrderDetailModel model = getCurrentOrder();
                        if (model != null) {
                            mStartTime = model.startTime;
                        }
                    }
                    startTimer(500);
                }
            }
        });
    }

    private void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }

    private void startTimer(int delay) {
        stopTimer();
        mTimer = new Timer("DISPLAY_TIME");
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                updateByTimer();
            }
        };
        mTimer.schedule(mTimerTask, delay);
    }

    private void startCountingTime() {
        mIsCountingTime = true;
        mStartTime = System.currentTimeMillis();
        OrderDetailModel model = getCurrentOrder();
        if (model != null) {
            model.startTime = mStartTime;
            model.save();
        }
        startTimer(500);
    }

    private void endCountingTime() {
        mIsCountingTime = false;
        OrderDetailModel model = getCurrentOrder();
        if (model != null) {
            model.waitTime += System.currentTimeMillis() - mStartTime;
            model.endTime = System.currentTimeMillis();
            model.save();
        }
        mTvTimeCalculate.setText("00:00:00");
        stopTimer();
    }

    private OrderDetailModel getCurrentOrder() {
        if (mOrderDetail != null) {
            List<OrderDetailModel> models = new Select().from(OrderDetailModel.class).where("orderId = ?", mOrderDetail.orderId).execute();
            if (models != null && models.size() > 0) {
                return models.get(0);
            }
            return null;
        }
        return null;
    }

    public void setRouteView(final OrderDetailInfo orderInfo) {
        if (mMapView != null) {
            mMapView.mBaiduMap.clear();
        }
        LatLng startPos = new LatLng(0, 0);
        LatLng endPos = new LatLng(0, 0);
        if (orderInfo != null) {

            List<OrderAddresses> addresses = orderInfo.orderAddresses;
            final List<LatLng> passLatLngs = new ArrayList<LatLng>();
            if (addresses != null && addresses.size() > 0) {
                for (int i = 0; i < addresses.size(); i++) {
                    OrderAddresses address = addresses.get(i);
                    if (OrderStatus.SHIPPER_ADDRESS.equals(address.flag)) {
                        startPos = new LatLng(address.latitude, address.longitude);
                        if (OrderStatus.N_TO_ONE.equals(orderInfo.transportMode)) {
                            passLatLngs.add(new LatLng(address.latitude, address.longitude));
                        }

                    } else if (OrderStatus.RECEIVER_ADDRESS.equals(address.flag)) {
                        endPos = new LatLng(address.latitude, address.longitude);
                        if (OrderStatus.ONE_TO_N.equals(orderInfo.transportMode)) {
                            passLatLngs.add(new LatLng(address.latitude, address.longitude));
                        }
                    }

                }
            }

            final LatLng start = startPos;
            final LatLng end = endPos;

            if (startPos.latitude > 1e-6 && startPos.longitude > 1e-6 && endPos.latitude > 1e-6 && endPos.longitude > 1e-6) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mMapView != null && mMapView.getMapView() != null) {
                            mMapView.getMapView().getMap().clear();
                        }
                        if (passLatLngs.size() > 1) {
                            mMapView.planRoute(start, end, passLatLngs.subList(0, passLatLngs.size() - 1), orderInfo.transportMode);
                        } else {
                            mMapView.planRoute(null, null, start, end, "start", "end");
                        }
                    }
                }, 100);
            }

        }
    }

    public void showCancelViewOrNot() {
        if (mOrderDetail != null) {
            // if (OrderStatus.WAIT_START.equals(mOrderDetail.status) || OrderStatus.STARTED.equals(mOrderDetail.status)) {
            if (true) {
                setBtnText(null, "遇到问题");
                mBtnRight.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        new OrderCancelDialog(OrderOperationActivity.this, "需要取消订单、调整地址顺序\n" + "请联系客服4008569900");
                    }
                });
            } else {
                setBtnText(null, null);
            }
        }
    }

    private void startCalculateFeeTimer(int delay) {
        stopCalculateTimer();
        mCalculateFeeTimer = new Timer("CALCULATE_FEE");
        mCalculateFeeTimerTask = new TimerTask() {
            @Override
            public void run() {
                updateCalculateFeeTimer();
            }
        };
        mCalculateFeeTimer.schedule(mCalculateFeeTimerTask, delay);
    }

    private void updateCalculateFeeTimer() {
        Logger.d("calculateFee", "fee");
        if (mIsDestroyed) {
            stopCalculateTimer();
        } else {
            if (mOrderDetail != null) {
                if (mOrderId != null) {
                    List<OrderDetailModel> models = new Select().from(OrderDetailModel.class).where("orderId = ?", mOrderId).execute();
                    if (models != null && models.size() > 0) {
                        OrderDetailModel model = models.get(0);
                        getOrderPrice(model);
                    }
                }
            }
            startCalculateFeeTimer(120000);
        }
    }

    private void stopCalculateTimer() {
        if (mCalculateFeeTimer != null) {
            mCalculateFeeTimer.cancel();
            mCalculateFeeTimer = null;
        }
        if (mCalculateFeeTimer != null) {
            mCalculateFeeTimer.cancel();
            mCalculateFeeTimer = null;
        }
    }

    private String getLatLngString(LatLng latLng) {
        return latLng.longitude + "," + latLng.latitude;
    }

    private void setPrice(double price, boolean isEst) {
        if (mOrderDetail != null) {
            if (isEst) {
                if (mOrderDetail.subsidy > 0.1) {
                    mTvCost.setText(Util.getOnePointNumber(price - mOrderDetail.subsidy) + "元(预估)＋" + Util.getOnePointNumber(mOrderDetail.subsidy)
                            + "元(补贴)");
                } else {
                    mTvCost.setText(Util.getOnePointNumber(price - mOrderDetail.subsidy) + "元(预估)");
                }
            } else {
                if (mOrderDetail.subsidy > 0.1) {
                    mTvCost.setText(Util.getOnePointNumber(price - mOrderDetail.subsidy) + "元＋" + Util.getOnePointNumber(mOrderDetail.subsidy)
                            + "元(补贴)");
                } else {
                    mTvCost.setText(Util.getOnePointNumber(price - mOrderDetail.subsidy) + "元");
                }
            }

            if(mOrderDetail.familiarPrice > 0.1) {
                mTvCost.setText(Util.getOnePointNumber(price) + "元(一口价)");
            }
        }
    }


}
